from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
from pydantic import BaseModel
from ..db.database import get_db
from ..models.workflow import Workflow
from ..models.user import User
from ..models.workflow_share import WorkflowShare
from ..schemas.workflow import WorkflowCreate, WorkflowResponse
from ..schemas.workflow_share import ShareWorkflowRequest, WorkflowShareResponse
from jose import jwt
from fastapi.security import OAuth2PasswordBearer
from ..core.config import settings
from sqlalchemy import or_

router = APIRouter()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")

# 获取当前用户工具函数
def get_current_user(db: Session, token: str):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="无法验证凭据",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
    except jwt.JWTError:
        raise credentials_exception
    user = db.query(User).filter(User.username == username).first()
    if user is None:
        raise credentials_exception
    return user

@router.post("/workflows/", response_model=WorkflowResponse)
def create_workflow(
    workflow: WorkflowCreate, 
    db: Session = Depends(get_db),
    token: str = Depends(oauth2_scheme)
):
    current_user = get_current_user(db, token)
    db_workflow = Workflow(**workflow.dict())
    db_workflow.user_id = current_user.id
    db.add(db_workflow)
    db.commit()
    db.refresh(db_workflow)
    return db_workflow

@router.get("/workflows/", response_model=List[WorkflowResponse])
def read_workflows(
    skip: int = 0, 
    limit: int = 100, 
    db: Session = Depends(get_db),
    token: str = Depends(oauth2_scheme)
):
    current_user = get_current_user(db, token)
    
    # 查询当前用户创建的工作流或共享给当前用户的工作流
    workflows = db.query(Workflow).filter(
        or_(
            # 用户自己创建的工作流
            Workflow.user_id == current_user.id,
            # 工作流被公开共享
            Workflow.id.in_(
                db.query(WorkflowShare.workflow_id).filter(WorkflowShare.is_public == True)
            ),
            # 工作流被共享给当前用户
            Workflow.id.in_(
                db.query(WorkflowShare.workflow_id).filter(WorkflowShare.user_id == current_user.id)
            )
        )
    ).offset(skip).limit(limit).all()
    
    return workflows

@router.get("/workflows/{workflow_id}", response_model=WorkflowResponse)
def read_workflow(
    workflow_id: int, 
    db: Session = Depends(get_db),
    token: str = Depends(oauth2_scheme)
):
    current_user = get_current_user(db, token)
    
    # 检查工作流权限：是创建者、共享者或公开工作流
    workflow = db.query(Workflow).filter(
        Workflow.id == workflow_id,
        or_(
            Workflow.user_id == current_user.id,
            Workflow.id.in_(
                db.query(WorkflowShare.workflow_id).filter(WorkflowShare.is_public == True)
            ),
            Workflow.id.in_(
                db.query(WorkflowShare.workflow_id).filter(WorkflowShare.user_id == current_user.id)
            )
        )
    ).first()
    
    if workflow is None:
        raise HTTPException(status_code=404, detail="Workflow not found")
    return workflow

@router.put("/workflows/{workflow_id}", response_model=WorkflowResponse)
def update_workflow(
    workflow_id: int, 
    workflow: WorkflowCreate, 
    db: Session = Depends(get_db),
    token: str = Depends(oauth2_scheme)
):
    current_user = get_current_user(db, token)
    db_workflow = db.query(Workflow).filter(Workflow.id == workflow_id, Workflow.user_id == current_user.id).first()
    if db_workflow is None:
        raise HTTPException(status_code=404, detail="Workflow not found")
    
    for key, value in workflow.dict().items():
        setattr(db_workflow, key, value)
    
    db.commit()
    db.refresh(db_workflow)
    return db_workflow

@router.delete("/workflows/{workflow_id}")
def delete_workflow(
    workflow_id: int, 
    db: Session = Depends(get_db),
    token: str = Depends(oauth2_scheme)
):
    current_user = get_current_user(db, token)
    workflow = db.query(Workflow).filter(Workflow.id == workflow_id, Workflow.user_id == current_user.id).first()
    if workflow is None:
        raise HTTPException(status_code=404, detail="Workflow not found")
    
    db.delete(workflow)
    db.commit()
    return {"message": "Workflow deleted successfully"}

class WorkflowCopyRequest(BaseModel):
    name: str
    description: Optional[str] = None

@router.post("/workflows/{workflow_id}/copy", response_model=WorkflowResponse)
def copy_workflow(
    workflow_id: int, 
    workflow_data: WorkflowCopyRequest, 
    db: Session = Depends(get_db),
    token: str = Depends(oauth2_scheme)
):
    current_user = get_current_user(db, token)
    # 找到原始工作流，并检查是否属于当前用户
    original_workflow = db.query(Workflow).filter(Workflow.id == workflow_id, Workflow.user_id == current_user.id).first()
    if original_workflow is None:
        raise HTTPException(status_code=404, detail="Workflow not found")
    
    # 创建新的工作流，复制原始工作流的所有属性
    new_workflow = Workflow(
        name=workflow_data.name,
        description=workflow_data.description,
        nodes=original_workflow.nodes,
        edges=original_workflow.edges,
        user_id=current_user.id
    )
    
    db.add(new_workflow)
    db.commit()
    db.refresh(new_workflow)
    return new_workflow

# 共享工作流API
@router.post("/workflows/{workflow_id}/share", response_model=List[WorkflowShareResponse])
def share_workflow(
    workflow_id: int,
    share_data: ShareWorkflowRequest,
    db: Session = Depends(get_db),
    token: str = Depends(oauth2_scheme)
):
    current_user = get_current_user(db, token)
    
    # 检查工作流是否存在且属于当前用户
    workflow = db.query(Workflow).filter(Workflow.id == workflow_id, Workflow.user_id == current_user.id).first()
    if workflow is None:
        raise HTTPException(status_code=404, detail="Workflow not found or you don't have permission")
    
    # 清除旧的共享记录
    db.query(WorkflowShare).filter(WorkflowShare.workflow_id == workflow_id).delete()
    
    shares = []
    
    # 如果是公开共享
    if share_data.is_public:
        public_share = WorkflowShare(
            workflow_id=workflow_id,
            user_id=None,
            is_public=True
        )
        db.add(public_share)
        shares.append(public_share)
    
    # 添加用户共享
    if share_data.user_ids:
        for user_id in share_data.user_ids:
            # 检查用户是否存在
            user = db.query(User).filter(User.id == user_id).first()
            if not user:
                continue  # 跳过不存在的用户
            
            # 不需要共享给自己
            if user_id == current_user.id:
                continue
                
            share = WorkflowShare(
                workflow_id=workflow_id,
                user_id=user_id,
                is_public=False
            )
            db.add(share)
            shares.append(share)
    
    db.commit()
    
    # 刷新数据
    for share in shares:
        db.refresh(share)
    
    return shares

# 获取所有可选的共享用户
@router.get("/users/for-sharing", response_model=List[dict])
def get_users_for_sharing(
    db: Session = Depends(get_db),
    token: str = Depends(oauth2_scheme)
):
    current_user = get_current_user(db, token)
    
    # 获取除当前用户外的所有用户
    users = db.query(User).filter(User.id != current_user.id).all()
    
    # 只返回id和用户名，避免暴露敏感信息
    return [{"id": user.id, "username": user.username, "full_name": user.full_name} for user in users]

# 获取工作流的共享信息
@router.get("/workflows/{workflow_id}/shares", response_model=List[WorkflowShareResponse])
def get_workflow_shares(
    workflow_id: int,
    db: Session = Depends(get_db),
    token: str = Depends(oauth2_scheme)
):
    current_user = get_current_user(db, token)
    
    # 检查工作流是否存在且属于当前用户
    workflow = db.query(Workflow).filter(Workflow.id == workflow_id, Workflow.user_id == current_user.id).first()
    if workflow is None:
        raise HTTPException(status_code=404, detail="Workflow not found or you don't have permission")
    
    shares = db.query(WorkflowShare).filter(WorkflowShare.workflow_id == workflow_id).all()
    return shares 